const Controller = require('egg').Controller;

class UserController extends Controller {
  // 注册
  async register() {
    const ctx = this.ctx;
    const {
      nickname,
      email,
      password,
      camera,
      avatar,
    } = ctx.request.body;

    const userId = await ctx.service.user.createUser({
      nickname,
      email,
      password,
      camera,
      avatar,
    });

    const activeId = await ctx.service.user.createActiveId({
      userId,
    });
    const activeUrl = `${this.config.servicePrefix}/api/user/active?id=${activeId}`;
    await ctx.service.user.email({
      from: `"Infinity" <${this.config.email.auth.user}>`,
      to: `"${nickname}" <${email}>`,
      subject: '【Infinity】账户激活',
      html: `
        <p>恭喜您成为 Infinity 的一员，请点击下方链接进行账户激活</p>
        <p><a href="${activeUrl}">${activeUrl}</a></p>
      `,
    });
    ctx.success({
      data: userId,
    });
  }

  // 激活
  async active() {
    const ctx = this.ctx;
    const {
      id,
    } = ctx.query;
    try {
      ctx.validate({
        id: {
          type: 'string',
          max: 36,
          min: 36,
        },
      }, {
        id,
      });
      const result = await ctx.service.user.activeUser(id);
      if (result) {
        ctx.type = 'html';
        ctx.body = `
          <html>
            <head>
              <title>激活成功</title>
              <meta http-equiv="refresh" content="3;URL=${this.config.servicePrefix}/login">
            </head>
            <body>
            激活成功，正在跳转到登录页
            </body>
          </html>
        `;
      } else {
        ctx.body = '激活码失败啦，可能是激活码不存在';
      }
    } catch (err) {
      ctx.body = '激活码错误';
    }
  }

  // 登录
  async login() {
    const { ctx } = this;
    try {
      ctx.validate({
        username: 'string',
        password: 'string',
      });
    } catch (err) {
      this.logger.error(err);
      ctx.throwError({
        code: 100004,
        msg: '参数错误',
      });
    }
    const user = await ctx.service.user.login(ctx.request.body);
    ctx.session.user = {
      userid: user.userid,
      nickname: user.nickname,
    };
    ctx.success({
      data: user,
    });
  }

  // 用户信息
  async userinfo() {
    const { ctx } = this;
    const user = await ctx.service.user.userinfo();
    ctx.success({
      data: user,
    });
  }

  // 修改用户信息
  async changeUser() {
    const { ctx } = this;
    ctx.validate({
      avatar: 'string',
      camera: 'string',
      intro: 'string',
    });
    const user = await ctx.service.user.changeUser(ctx.request.body);
    ctx.success({
      data: user,
    });
  }

  // 登出
  async logout() {
    const ctx = this.ctx;
    if (ctx.session) { ctx.session = null; }
    ctx.redirect('/login');
  }
}


module.exports = UserController;
